<?php
if(!defined('CMS'))die;
global $Eleanor, $head, $title;
$Eleanor->module['config'] = include($Eleanor->module['path'].'config.php');
$l = Eleanor::$Language->Load($Eleanor->module['path'].'lang_user-*.php',$Eleanor->module['config']['n']);
$Eleanor->module['etag'] = '';

$Lst = Eleanor::LoadListTemplate('headfoot');
$u = '?'.Url::Query(Eleanor::$vars['multilang'] && Language::$main!=LANGUAGE ? array('lang'=>Eleanor::$langs[Language::$main]['uri'],'module'=>$Eleanor->module['name']) : array('module'=>$Eleanor->module['name']));
$Eleanor->module['rss']=Eleanor::$services['rss']['file'].$u;
$head['rss']=$Lst->link(array(
	'rel'=>'alternate',
	'type'=>'application/rss+xml',
	'href'=>$Eleanor->module['rss'],
	'title'=>$l['question'],
));
$head['search']=$Lst->link(array(
	'rel'=>'search',
	'type'=>'application/opensearchdescription+xml',
	'title'=>$l['question'],
	'href'=>Eleanor::$services['xml']['file'].$u,
));

Eleanor::LoadOptions($Eleanor->module['config']['opts']);
Eleanor::$Template->queue[]=$Eleanor->module['config']['usertpl'];

$curls=array();
$question='';
if($Eleanor->Url->is_static)
{
	$question=false;
	$str=$Eleanor->Url->GetEnding(array($Eleanor->Url->ending,$Eleanor->Url->delimiter),true);
	$_GET+=$Eleanor->Url->Parse($str ? array() : array('do'));
	if($str)
	{
		$curls=isset($_GET['']) ? (array)$_GET[''] : array();
		if($str==$Eleanor->Url->ending and !isset($_GET['page']))
			$question=array_pop($curls);
	}
}
$cid=isset($_GET['cid']) ? (int)$_GET['cid'] : 0;
$nid=isset($_GET['nid']) ? (int)$_GET['nid'] : 0;

$Eleanor->Categories->Init($Eleanor->module['config']['c']);

if(isset($_GET['do'])) {
	$d=(string)$_GET['do'];
	switch($d) {
		case'my':
			if(Eleanor::$Login->IsUser()) {
				$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['my'];
				$uid=Eleanor::$Login->GetUserValue('id');
				$R = Eleanor::$Db->Query('SELECT COUNT(`author_id`) FROM `'.$Eleanor->module['config']['t'].'` WHERE `author_id`='.$uid);
				list($cnt)=Eleanor::$Db->FetchRow();

				$page=isset($_GET['page']) ? (int)$_GET['page'] : 1;
				if($page<1)
					$page=1;
				$offset=($page-1)*$cnt;

				if($cnt and $offset>=$cnt)
					$offset=max(0,$cnt-Eleanor::$vars['publ_per_page']);
				$r=$R = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`reads`,`comments`,`status`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN("","'.Language::$main.'") AND `author_id`='.$uid.' ORDER BY `ldate` DESC LIMIT '.$offset.', '.Eleanor::$vars['publ_per_page']);
				$d=QuestionList($r);
				if(!$d)
					return;
				$c=Eleanor::$Template->QuestionAuthorList($d,$cnt,$page,Eleanor::$vars['publ_per_page']);
				Start();
				echo$c;
			}
			else
				QuestionBeginPage();
		break;
		case'edit':
		case'delete':
			if($Eleanor->Url->is_static)
				$id=(isset($_GET['']) and is_array($_GET[''])) ? (int)reset($_GET['']) : false;
			else
				$id=isset($_GET['id']) ? (int)$_GET['id'] : false;
			if(Eleanor::$Login->IsUser())
				switch($d)
				{
					case'edit':
						GoAway();
					break;
					case'delete':
						$uid=(int)Eleanor::$Login->GetUserValue('id');
						$R = Eleanor::$Db->Query('SELECT `id`,`title`,`author_id` FROM `'.$Eleanor->module['config']['t'].'` LEFT JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `id`='.$id.' AND `language` IN ("","'.Language::$main.'") LIMIT 1');
						if(!$arr=$R->fetch_assoc() or !Eleanor::$our_query or !Eleanor::$Permissions->IsAdmin() and $arr['author_id']!=$uid or $uid==0)
							return GoAway(true);
						if(isset($_POST['ok'])) {
							if($arr['voting'])
								$Eleanor->Voting_Manager->Delete($arr['voting']);
							Files::Delete(Eleanor::$root . Eleanor::$uploads . DIRECTORY_SEPARATOR.$Eleanor->module['config']['n'].DIRECTORY_SEPARATOR.$id);
							Eleanor::$Db->Delete(P .'comments','`module`='.$Eleanor->module['id'].' AND `contid`'.Eleanor::$Db->In($_POST['mass']));
							Eleanor::$Db->Delete($Eleanor->module['config']['t'],'`id`='.$id.' LIMIT 1');
							Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`='.$id);
							Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
							$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['deleted'];
							$c=Eleanor::$Template->QuestionDelSuccess($arr,empty($_POST['back']) ? false : $_POST['back']);
						} else {
							$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['del_confirm'];
							if(isset($_GET['noback']))
								$back='';
							else
								$back=isset($_POST['back']) ? (string)$_POST['back'] : getenv('HTTP_REFERER');
							$c=Eleanor::$Template->DeleteQuestion($arr,$back);
						}
						Start();
						echo$c;
				}
			else
				QuestionBeginPage();
		break;
		case'categories':
			if(!$Eleanor->Categories->dump)
				return GoAway();
			global$title;
			$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['categs'];
			$c=Eleanor::$Template->ShowCategories();
			Start();
			echo$c;
		break;
		default:
			if(preg_match('#^(\d{4})\D(\d{1,2})(?:\D(\d{1,2}))?$#',$d,$ma)>0)
			{
				if(strtotime($d)>time())
					return GoAway(true);
				$title[]=sprintf(Eleanor::$Language[$Eleanor->module['config']['n']]['question_for'],Eleanor::$Language->Date($d,strlen($d)>7 ? 'fd' : 'my',array('lowercase'=>true)));
				$R = Eleanor::$Db->Query('SELECT COUNT(`lstatus`) FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN("","'.Language::$main.'") AND `lstatus`=1 AND IF(`pinned` IS NULL,`date`,`pinned`) LIKE "'.$d.'%"');
				list($cnt)=Eleanor::$Db->FetchRow();

				$np=$cnt % Eleanor::$vars['publ_per_page'];
				$pages=max(ceil($cnt/Eleanor::$vars['publ_per_page'])-($np>0 ? 1 : 0),1);
				$page=isset($_GET['page']) ? (int)$_GET['page'] : $pages;
				$intpage=$pages - $page + 1;
				$offset=max(0,$intpage-1)*Eleanor::$vars['publ_per_page'];

				$limit=Eleanor::$vars['publ_per_page'];
				if($offset==0)
					$limit+=$np;
				else
					$offset+=$np;

				if($cnt and $offset>=$cnt)
					$offset=max(0,$cnt-$limit);
				$r=$R = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`reads`,`comments`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN("","'.Language::$main.'") AND `lstatus`=1 AND IF(`pinned` IS NULL,`date`,`pinned`) LIKE "'.$d.'%" ORDER BY `ldate` DESC LIMIT '.$offset.', '.$limit);
				$data=QuestionList($r);
				if(!$data)
					return;
				$c=Eleanor::$Template->QuestionDateList($d,$data,$cnt-$np,$page,Eleanor::$vars['publ_per_page']);
				$Eleanor->origurl=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct(array('do'=>$d),true,'');
				Start();
				echo$c;
			}
			else
				ExitPage();
	}
} elseif($nid or $question) {
	$where = $nid ? '`id`='.(int)$nid : '`uri`="'.Eleanor::$Db->Escape($question,false).'"';
	$uid=(int)Eleanor::$Login->GetUserValue('id');

	if($uid==0)
	{
		$gn=Eleanor::GetCookie($Eleanor->module['config']['n'].'-gn');
		$gns=Eleanor::GetCookie($Eleanor->module['config']['n'].'-gns');

		if($gn and $gns and $gns===md5($gn.$Eleanor->module['config']['secret']))
			$gn=explode(',',$gn);
		else
			$gn=array();
	}
	else
		$gn=array();

	$R = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`show_sokr`,`reads`,`comments`,`status`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN("","'.Language::$main.'") AND '.$where.' LIMIT 1');
	if(!$arr=$R->fetch_assoc() or ($arr['status']!=1 and (!Eleanor::$Permissions->IsAdmin() and $arr['author_id']!=$uid or $uid==0 and !in_array($arr['id'],$gn))))
		return ExitPage();
	$arr['_cat']=$arr['cats'] ? (int)ltrim($arr['cats'],',') : false;
	$u=array('u'=>array($arr['uri'],'nid'=>$arr['id']));
	if($arr['_cat'] and $Eleanor->Url->furl)
	{
		$cu=$Eleanor->Categories->GetUri($arr['_cat']);
		if($cu)
			$u=$cu+$u;
	}
	if($cid or $curls or $nid and $arr['uri'])
	{
		$category=$Eleanor->Categories->GetCategory($cid,$curls);
		if($category and $category['id']!=$arr['_cat'])
		{
			$commu=$Eleanor->Comments->GET();
			foreach($commu as $k=>$v)
				$u[]=array($k=>$v);
			return GoAway($u);
		}
	}
	if(!Eleanor::$is_bot and $arr['status']==1)
	{
		$ref=getenv('HTTP_REFERER');
		$uu=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct($u,true,'');
		$uu=htmlspecialchars_decode($uu,ENT_QUOTES);
		if(strpos($ref,$uu)===false)
			Eleanor::$Db->Update($Eleanor->module['config']['t'],array('!reads'=>'`reads`+1'),'`id`='.$arr['id'].' LIMIT 1');
	}

	if(Eleanor::$caching)
	{
		Eleanor::$last_mod=$arr['last_mod'];
		$etag=Eleanor::$etag;
		$uid=Eleanor::$Login->GetUserValue('id');
		Eleanor::$etag=md5($uid.'-'.$arr['id'].'-'.$Eleanor->module['config']['n'].$Eleanor->module['etag']);
		if(Eleanor::$modified and Eleanor::$last_mod and Eleanor::$last_mod<=Eleanor::$modified and $etag and $etag==Eleanor::$etag)
			return Start();
		else
			Eleanor::$modified=false;
	}

	$title[]=$arr['title'];

	OwnBB::$opts['alt']=$arr['title'];
	$Eleanor->origurl=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct($u);

	$arr['text']=OwnBB::Parse($arr['text']);
	#Поддержка соцсетей:
	$Lst=Eleanor::LoadListTemplate('headfoot')
		->og('title',$arr['title'])
		->og('uri',$Eleanor->origurl)
		->og('locale',Eleanor::$langs[Language::$main]['d'])
		->og('site_name',Eleanor::$vars['site_name']);
	if(preg_match('#<img.+?src="([^"]+)"[^>]*>#',$arr['text'], $m) > 0)
		$Lst->og('image', strpos($m[1],'://')===false ? PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$m[1] : $m[1]);
	$GLOBALS['head']['og']=(string)$Lst;

	if(!$Eleanor->Comments->off)
		$Eleanor->Comments->baseurl = array('module' => $Eleanor->module['name']) + $u;
	$hl=isset($_GET['hl']) && is_string($_GET['hl']) && preg_match('#^[a-z0-9'.constant(Language::$main.'::ALPHABET').' ]+$#i',$_GET['hl'])>0 ? preg_split('/\s+/',$_GET['hl']) : false;
    $arr += array('navi' => $Eleanor->Categories->BreadCrumbs($arr['_cat'], $Eleanor->module['config']['c'], $Eleanor->module['config']['cl']));
	$c = Eleanor::$Template->ShowQuestion($arr, $Eleanor->Comments->off ? '' : $Eleanor->Comments->Show($arr['id'], $hl));
	Start();
	echo$c;
} elseif($cid || $curls) {
	$category=$Eleanor->Categories->GetCategory($cid ? $cid : $curls);
	if(!$category)
		return ExitPage();
	$Lst=Eleanor::LoadListTemplate('headfoot');
	$head['rss']=$Lst->link(array(
		'rel'=>'alternate',
		'type'=>'application/rss+xml',
		'href'=>Eleanor::$services['rss']['file'].'?'.Url::Query(Eleanor::$vars['multilang'] && Language::$main!=LANGUAGE ? array('lang'=>Eleanor::$langs[Language::$main]['uri'],'module'=>$Eleanor->module['name'],'c'=>$category['id']) : array('module'=>$Eleanor->module['name'],'c'=>$category['id'])),
		'title'=>sprintf(Eleanor::$Language[$Eleanor->module['config']['n']]['questionfrom'],$category['title']),
	));
	if($category['meta_title'])
		$title=$category['meta_title'];
	else
		$title[]=$category['title'];

	if($category['meta_descr'])
		$Eleanor->module['description']=$category['meta_descr'];

	if(Eleanor::$vars['publ_catsubcat']) {
		$carr=array($category['id']);
		$p=$category['parents'].$category['id'].',';
		foreach($Eleanor->Categories->dump as $k=>&$v)
			if(strpos($v['parents'],$p)===0)
				$carr[]=$k;
		$cwhere=count($carr)>1 ? 'REGEXP (",('.join('|',$carr).'),")' : 'LIKE "%,'.$category['id'].',%"';
	} else
		$cwhere='LIKE "%,'.$category['id'].',%"';
	$R = Eleanor::$Db->Query('SELECT COUNT(`lstatus`) FROM `'.$Eleanor->module['config']['tl'].'` WHERE `language`IN("","'.Language::$main.'") AND `lstatus`=1 AND `lcats` '.$cwhere.'');
	list($cnt) = $R->fetch_row();

	$np=$cnt % Eleanor::$vars['publ_per_page'];
	$pages=max(ceil($cnt/Eleanor::$vars['publ_per_page'])-($np>0 ? 1 : 0),1);
	$page=isset($_GET['page']) ? (int)$_GET['page'] : $pages;
	$intpage=$pages - $page + 1;
	$offset=max(0,$intpage-1)*Eleanor::$vars['publ_per_page'];

	$limit=Eleanor::$vars['publ_per_page'];
	if($offset==0)
		$limit+=$np;
	else
		$offset+=$np;
	if($cnt and $offset>=$cnt)
		$offset=max(0,$cnt-$limit);
	$r = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`reads`,`comments`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN("","'.Language::$main.'") AND `lstatus`=1 AND `lcats` '.$cwhere.' ORDER BY `ldate` DESC LIMIT '.$offset.', '.$limit);
	$d = QuestionList($r);
	if(!$d)
		return;

	$c = Eleanor::$Template->QuestionCategoryList($category, $d, $cnt - $np, $page, Eleanor::$vars['publ_per_page']);
	$Eleanor->origurl = PROTOCOL.Eleanor::$punycode . Eleanor::$site_path . $Eleanor->Url->Construct($Eleanor->Categories->GetUri($category['id']) + array('page' => array('page' => $page == $pages ? false : $page)), true, $Eleanor->Url->delimiter);
	Start();
	echo$c;
} else
	QuestionBeginPage();

function Save(array $data) {
global$Eleanor;

	$maincat = isset($data['modeli']) ? (int)$data['modeli'] : false;
	$cats = isset($data['marki']) ? array($data['marki'], $maincat) : array();
	if($cats and count($cats)>1) {
		sort($cats, SORT_NUMERIC);
		if($maincat != $cats[0])
			array_unshift($cats ,$maincat ? $maincat : reset($cats));
	}
	$cats = $cats ? ','.join(',,',$cats).',' : '';

	$url = htmlspecialchars_decode($data['question'], ENT_QUOTES);
	$url = $Eleanor->Url->Filter($url);

	$values = array(
				'cats' => $cats,
				'date' => date('Y-m-d H:i:s'),
				'author' => (string)Eleanor::$Login->GetUserValue('name'),
				'author_id' => (int)Eleanor::$Login->GetUserValue('id'),
				'show_detail' => date('Y-m-d H:i:s'),
				'status' => 1,
				'email' => (string)$data['email'],
			);

	$values_l = array(
				'id' => Eleanor::$Db->Insert($Eleanor->module['config']['t'], $values, null),
				'language' => Language::$main,
				'lstatus' => 1,
				'uri' => $url,
				'ldate' => date('Y-m-d H:i:s'),
				'lcats' => $cats,
				'title' => $data['question'],
				'text' => $data['text'],
				);
	Eleanor::$Db->Insert($Eleanor->module['config']['tl'], $values_l, null);
	return true;
}

function QuestionBeginPage() {
	global$Eleanor, $title;
	$lang = Eleanor::$Language[$Eleanor->module['config']['n']];
	$title[] = $lang['question'];
	$marki = '';
	$q = Eleanor::$Db->Query('SELECT `id`, `title` FROM `'. $Eleanor->module['config']['c'] .'` INNER JOIN `'. $Eleanor->module['config']['cl'] .'` USING(`id`) WHERE `published`=1 AND `parent` = 0');
    while ($v = $q->fetch_assoc()) {
        $marki .= '<li data-id="'. $v['id'] .'">'. $v['title'] .'</li>';
    }
	$c = '';

	$R = Eleanor::$Db->Query('SELECT COUNT(*) FROM `'. $Eleanor->module['config']['t'] .'` WHERE `status` = 1');
	list($cnt) = $R->fetch_row();

	$np = $cnt % Eleanor::$vars['publ_per_page'];
	$pages = max(ceil($cnt / Eleanor::$vars['publ_per_page']) - ($np > 0 ? 1 : 0), 1);
	$page = isset($_GET['page']) ? (int)$_GET['page'] : $pages;
	$intpage = $pages - $page + 1;
	$offset = max(0, $intpage - 1) * Eleanor::$vars['publ_per_page'];

	$limit = Eleanor::$vars['publ_per_page'];
	if($offset==0)
		$limit += $np;
	else
		$offset += $np;

	if($cnt and $offset >= $cnt)
		$offset = max(0, $cnt-$limit);

	$R = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`reads`,`comments`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `'. $Eleanor->module['config']['t'] .'` INNER JOIN `'. $Eleanor->module['config']['tl'] .'` USING(`id`) WHERE `language`IN("", "'.Language::$main.'") AND `lstatus`=1 ORDER BY `ldate` DESC LIMIT '. $offset .', '. $limit);
	if(!$d = QuestionList($R, empty($Eleanor->module['general'])))
		return;
	if (!isset($_GET['page'])) {
		$c = Eleanor::$Template->DisplayQuestion($marki, $lang);
	}
	$links = array(
		'first_page' => $Eleanor->Url->Prefix(false),
		'pages' => function($n) { return $GLOBALS['Eleanor']->Url->Construct(array(array('page' => $n))); },
	);
	$c .= Eleanor::$Template->QuestionList($d, $cnt - $np, -$page, $pages, Eleanor::$vars['publ_per_page'], $links);
	$Eleanor->origurl = PROTOCOL . Eleanor::$punycode . Eleanor::$site_path . $Eleanor->Url->Construct(array('page' => array('page' => $page == $pages ? false : $page)));
	Start();
	echo$c;
}

function QuestionList($R, $caching=true, $anurl=array()) {
	global$Eleanor;
	$items=$ucats=array();
	$lmod=0;
	$ids=',';
	$uid=Eleanor::$Login->GetUserValue('id');
	while($arr=$R->fetch_assoc()) {
		$ids.=$arr['id'].',';
		if($arr['last_mod']>$lmod)
			$lmod=$arr['last_mod'];

		$arr['_cat']=$arr['cats'] ? (int)ltrim($arr['cats'],',') : false;
		if($arr['_cat'] and !isset($ucats[$arr['_cat']]))
			$ucats[$arr['_cat']]=$Eleanor->Categories->GetUri($arr['_cat']);

		OwnBB::$opts['alt']=$arr['title'];
		$arr['text']=OwnBB::Parse($arr['text']);

		$u = array('u' => array($arr['uri'], 'nid' => $arr['id'])) + $anurl;
		$arr['_url'] = $Eleanor->Url->Construct($arr['_cat'] && $Eleanor->Url->furl && isset($ucats[$arr['_cat']]) ? $ucats[$arr['_cat']]+$u : $u);
        //calculate comments
        $comments_count = Eleanor::$Db->Query('SELECT COUNT(*) FROM `el_comments` WHERE `module` ="'. $Eleanor->module['id'] .'" AND `contid` = '. $arr['id'] .' AND `status` = 1 LIMIT 1')->fetch_row();
        $arr += array('comments_count' => $comments_count[0]);
		$navi = $Eleanor->Categories->BreadCrumbs($arr['_cat'], $Eleanor->module['config']['c'], $Eleanor->module['config']['cl']);
		$items[]= ($navi ? $arr + array('navi' => $navi) : $arr);
	}

	if($caching and Eleanor::$caching) {
		Eleanor::$last_mod = $lmod;
		$etag = Eleanor::$etag;
		Eleanor::$etag = md5($uid . $ids . $Eleanor->module['config']['n'] . $Eleanor->module['etag']);
		if(Eleanor::$modified and Eleanor::$last_mod and Eleanor::$last_mod <= Eleanor::$modified and $etag and $etag == Eleanor::$etag)
			return Start();
		else
			Eleanor::$modified = false;
	}

	foreach($ucats as &$v)
		$v=$Eleanor->Url->Construct($v,true,$Eleanor->Url->delimiter);

	return compact('items','ucats');
}